package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    private Socket socket;
    public Client(){
        try {
            socket=new Socket("localhost",8080);
            System.out.println("连接成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        //
        try {

            // 1. 获取输出流
            OutputStream os=socket.getOutputStream();
            OutputStreamWriter osw=new OutputStreamWriter(os, StandardCharsets.UTF_8);
            BufferedWriter bf=new BufferedWriter(osw);
            PrintWriter pw=new PrintWriter(bf,true);

            Scanner scanner=new Scanner(System.in);
            System.out.println("请输入昵称:");
            String nickname=scanner.nextLine();
            while (nickname.trim().isEmpty()){
                System.out.println("昵称不能为空，请重新输入:");
                nickname=scanner.nextLine();
            }
            pw.println(nickname);

            Runnable handler= new ServerHandler();
            Thread thread=new Thread(handler);
            thread.setDaemon(true);
            thread.start();


            //主线程用于循环发送消息
            while (true){
                String message =scanner.nextLine();
                if (message.trim().isEmpty()){
                    System.out.println("消息不能为空，请重新输入:");
                    continue;
                }
                if ("exit".equals(message)){
                    break;
                }
                pw.println(message);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        Client client=new Client();
        client.start();
    }

    public class ServerHandler implements Runnable{

        public void run() {

            try {
                // 2. 获取输入流
                InputStream is=socket.getInputStream();
                InputStreamReader isr=new InputStreamReader(is,StandardCharsets.UTF_8);
                BufferedReader br=new BufferedReader(isr);

                String message;
                while ((message=br.readLine())!=null){
                    System.out.println(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
